//
//  APDeleteAndEditPhotoViewController.m
//  APlan
//
//  Created by he15his on 14/10/20.
//  Copyright (c) 2014年 jingling. All rights reserved.
//

#import "SLDeleteAndSelectPhotoViewController.h"
#import "SLPhotoCollectionViewController.h"
#import <objc/runtime.h>
#import "JFBase.h"
#import "JFBasePri.h"


#define kBottomViewHeight 50.0

NSString *const kCellReuseIdentifier = @"cell";

@interface SLDeleteAndSelectPhotoViewController ()<UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UIGestureRecognizerDelegate> {
    NSMutableArray *_thumbImages;
    NSMutableArray *_urls;
    NSInteger _currentImageIndex;
    NSMutableArray *_selectAssets;
    NSMutableArray *_allAssets;
    NSInteger _maxImageNumber;
    BOOL _isDeleteModel;
    NSInteger _otherPhotoCount; //拍摄的照片数量
}
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) UILabel *headLabel;
@property (nonatomic, strong) UILabel *numLabel;
@property (nonatomic, weak) id<SLDeleteAndEditPhotoViewControllerDelegate> delegate;
@end

@implementation SLDeleteAndSelectPhotoViewController

- (instancetype)initDeleteModelWithThumbImages:(NSMutableArray *)thumbImages
                                          urls:(NSMutableArray *)urls
                             currentImageIndex:(NSInteger)currentImageIndex
                                      delegate:(id<SLDeleteAndEditPhotoViewControllerDelegate>)delegate {
    self = [super init];
    if (self) {
        _thumbImages = thumbImages;
        _urls = urls;
        _currentImageIndex = currentImageIndex;
        _delegate = delegate;
        _isDeleteModel = YES;
    }
    return self;
}

- (instancetype)initSelectModelWithAllAssets:(NSMutableArray *)allAssets
                                selectAssets:(NSMutableArray *)selectAssets
                           currentImageIndex:(NSInteger)currentImageIndex
                              maxImageNumber:(NSInteger)maxImageNumber
                                 thumbImages:(NSMutableArray *)thumbImages
                                    hdImages:(NSMutableArray *)hdImages
                                        urls:(NSMutableArray *)urls
                                    delegate:(id<SLDeleteAndEditPhotoViewControllerDelegate>)delegate {
    self = [super init];
    if (self) {
        _selectAssets = selectAssets;//不重新生成对象，返回后直接刷新上个页面就是了
        _allAssets = [NSMutableArray arrayWithArray:allAssets];
        _currentImageIndex = currentImageIndex;
        _maxImageNumber = maxImageNumber;
        _thumbImages = thumbImages;
        _urls = urls;
        _delegate = delegate;
        _otherPhotoCount = thumbImages.count - selectAssets.count;
    }
    return self;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.translucent = NO;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];
    if (@available(iOS 11.0, *)) {
        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }

    [self createSubViews];
}

- (void)createSubViews{
    CGFloat width = CGRectGetWidth([UIScreen mainScreen].bounds);
    
    //顶部View
    _headLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 44)];
    _headLabel.textAlignment = NSTextAlignmentCenter;
    _headLabel.textColor = HexColor(@"#ffffff");
    _headLabel.font = [UIFont systemFontOfSize:15];
        _headLabel.backgroundColor = [UIColor clearColor];
    _headLabel.userInteractionEnabled = YES;
    self.navigationItem.titleView = _headLabel;
    [self resetRightButton];

    if (!_isDeleteModel) {
        _headLabel.text = [NSString stringWithFormat:@"%ld/%lu", (long)_currentImageIndex+1, (unsigned long)_allAssets.count];
    }else {
        _headLabel.text = [NSString stringWithFormat:@"%ld/%lu", (long)_currentImageIndex+1, (unsigned long)_urls.count];
    }
    [self.view addSubview:self.collectionView];
    //底部view
    [self.view addSubview:self.bottomView];
    [_collectionView setContentOffset:CGPointMake(_currentImageIndex*width, 0) animated:NO];
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _isDeleteModel ? _urls.count : _allAssets.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCellReuseIdentifier forIndexPath:indexPath];
    
    if ([collectionView.visibleCells containsObject:cell]) {
        return cell;
    }
    
    UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:100];
    if (!imageView) {
        CGFloat width = CGRectGetWidth([UIScreen mainScreen].bounds);
        CGFloat height = CGRectGetHeight([UIScreen mainScreen].bounds);
        UIScrollView *imageScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
        imageScrollView.bounces = NO;
        imageScrollView.showsHorizontalScrollIndicator = NO;
        imageScrollView.showsVerticalScrollIndicator = NO;
        imageScrollView.backgroundColor = [UIColor colorWithHexString:@"#eaebec"];
        imageScrollView.delegate = self;
        imageScrollView.maximumZoomScale = 3.0;
        imageScrollView.minimumZoomScale = 1.0;
        imageScrollView.tag = 101;
        [cell.contentView addSubview:imageScrollView];
        
        imageView = [[UIImageView alloc] init];
        imageView.frame = imageScrollView.bounds;
        imageView.tag = 100;
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [imageScrollView addSubview:imageView];
    }
    UIScrollView *imageScrollView = (UIScrollView *)[cell.contentView viewWithTag:101];
    [imageScrollView setZoomScale:1.0 animated:NO];
    imageView.image = nil;
    
    if (_isDeleteModel) {
        void (^imageHandler)(void) = ^{
            CGFloat width = imageView.image.size.width;
            CGFloat height = imageView.image.size.height;
            if (width > CGRectGetWidth(imageScrollView.frame)) {
                height = CGRectGetWidth(imageScrollView.frame) * height / width;
                width = CGRectGetWidth(imageScrollView.frame);
            }
            if (height > CGRectGetHeight(imageScrollView.frame)) {
                width = CGRectGetHeight(imageScrollView.frame) * width / height;
                height = CGRectGetHeight(imageScrollView.frame);
            }
            imageView.frame = CGRectMake(0, 0, width, height);
            imageView.center = imageScrollView.center;
        };
        
        id obj = _urls[indexPath.row];
        if ([obj isKindOfClass:[UIImage class]]) {
            imageView.image = obj;
            imageHandler();
        }else {
            [JFALImagePicker pickImageWithUrl:obj resultBlock:^(UIImage *image) {
                imageView.image = image;
                imageHandler();
            }];
        }
    }else {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            ALAsset *result = _allAssets[indexPath.row];
            UIImage *img = nil;
            CGImageRef ref = [[result  defaultRepresentation] fullScreenImage];
            img = [[UIImage alloc]initWithCGImage:ref];

            dispatch_async(dispatch_get_main_queue(), ^{
                imageView.image = img;

                CGFloat width = imageView.image.size.width;
                CGFloat height = imageView.image.size.height;
                if (width > CGRectGetWidth(imageScrollView.frame)) {
                    height = CGRectGetWidth(imageScrollView.frame) * height / width;
                    width = CGRectGetWidth(imageScrollView.frame);
                }
                if (height > CGRectGetHeight(imageScrollView.frame)) {
                    width = CGRectGetHeight(imageScrollView.frame) * width / height;
                    height = CGRectGetHeight(imageScrollView.frame);
                }
                imageView.frame = CGRectMake(0, 0, width, height);
                imageView.center = imageScrollView.center;
            });
        });
        
        
    }
    return cell;
}

#pragma mark - UICollectionViewDelegate

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetHeight([UIScreen mainScreen].bounds));
}

//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

//最小行距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}


#pragma mark - UIScrollViewDelegate
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    if ([scrollView isEqual:_collectionView])
    {
        return nil;
    }
    return [scrollView.subviews objectAtIndex:0];
}

//负责缩小后的中心点偏移
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    if (![scrollView isEqual:_collectionView])
    {
        UIView *subView = [scrollView.subviews objectAtIndex:0];
        
        CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
        (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
        
        CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
        (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
        
        subView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
                                     scrollView.contentSize.height * 0.5 + offsetY);
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if ([scrollView isEqual:_collectionView])
    {
        CGFloat width = CGRectGetWidth(scrollView.frame);
        NSInteger number = scrollView.contentOffset.x/width;
        _currentImageIndex = number;
        
        if (!_isDeleteModel) {
            _headLabel.text = [NSString stringWithFormat:@"%ld/%lu", (long)number+1, (unsigned long)_allAssets.count];
        }else {
            _headLabel.text = [NSString stringWithFormat:@"%ld/%lu", (long)number+1, (unsigned long)_urls.count];
        }
        [self resetRightButton];
    }
}


#pragma mark - Event Handle

- (void)popViewController{
    if (self.delegate && [self.delegate respondsToSelector:@selector(popWithThumbImages:urls:)]) {
        
        //预览未选择时取当前图片
        if (!_isDeleteModel) {
            if (_urls.count == 0) {
                ALAsset *result = _allAssets[_currentImageIndex];
                NSURL *url = [[result  defaultRepresentation] url];
                UIImage *thumbnail = [[UIImage alloc] initWithCGImage:result.thumbnail];
                
                [_thumbImages addObject:thumbnail];
                [_urls addObject:url];
            }
        }
        [self.delegate popWithThumbImages:_thumbImages urls:_urls];
    }
    
    UIViewController *frontCtl = self.navigationController.viewControllers[self.navigationController.viewControllers.count-3];
    
    if (!_isDeleteModel) {
        self.navigationController.navigationBar.translucent = NO;
        self.automaticallyAdjustsScrollViewInsets = YES;
        [self.navigationController popToViewController:frontCtl animated:YES];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)hiddenOrDisplayBarHandel {
    
    if (![self.navigationController.navigationBar isHidden]) {
        //隐藏
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        [self setNeedsStatusBarAppearanceUpdate];
        [UIView animateWithDuration:0.3 animations:^{
            _bottomView.frame = CGRectMake(0, CGRectGetHeight([UIScreen mainScreen].bounds), CGRectGetWidth([UIScreen mainScreen].bounds), kBottomViewHeight);
        }];
    }else {
        //显示
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        [self setNeedsStatusBarAppearanceUpdate];
        [UIView animateWithDuration:0.3 animations:^{
            _bottomView.frame = CGRectMake(0, CGRectGetHeight([UIScreen mainScreen].bounds) - kBottomViewHeight, CGRectGetWidth([UIScreen mainScreen].bounds), kBottomViewHeight);
        }];
    }
}

- (void)rightBarButtonClicked:(UIButton *)sender{
    
    if (!_isDeleteModel) {
        //可选择的模式
        CGFloat width = CGRectGetWidth(_collectionView.frame);
        NSInteger number = _collectionView.contentOffset.x/width;
        if ([_selectAssets containsObject:_allAssets[number]]) {
            //不选中
            NSInteger index = [_selectAssets indexOfObject:_allAssets[number]];
            [_selectAssets removeObjectAtIndex:index];
            [_urls removeObjectAtIndex:index + _otherPhotoCount];
            [_thumbImages removeObjectAtIndex:index + _otherPhotoCount];
        }else {
            //选中
            if (_thumbImages.count < _maxImageNumber) {
                [_selectAssets addObject:_allAssets[number]];
                
                ALAsset *result = _allAssets[number];
                NSURL *url = [[result  defaultRepresentation] url];
                UIImage *thumbnail = [[UIImage alloc] initWithCGImage:result.thumbnail];
                
                [_thumbImages addObject:thumbnail];
                [_urls addObject:url];
            }else {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:JFBaseLocalizedString(@"me.chosePhoto"), _selectAssets.count] message:nil delegate:nil cancelButtonTitle:JFBaseLocalizedString(@"我知道了") otherButtonTitles:nil, nil];
                [alertView show];
            }
        }
        [self setNumLabelContent];
        [self resetRightButton];
        return;
    }
    
    CGFloat width = CGRectGetWidth(_collectionView.frame);
    NSInteger number = _collectionView.contentOffset.x/width;
    [_thumbImages removeObjectAtIndex:number];
    [_urls removeObjectAtIndex:number];
    
    if(number > _urls.count - 1){
        number = _urls.count - 1;
    }
    
    _headLabel.text = [NSString stringWithFormat:@"%ld/%lu", (long)number+1, (unsigned long)_urls.count];
    
    if (_urls.count == 0) {
        [self popViewController];
    }else {
        [self setNumLabelContent];
    }
    [_collectionView reloadData];
}


#pragma mark - Private Method

- (void)setNumLabelContent {
    
    if (_isDeleteModel) {
        _numLabel.hidden = _urls.count == 0;
        _numLabel.text = [NSString stringWithFormat:@"%lu",(unsigned long)_urls.count];
    }else {
        _numLabel.hidden = _selectAssets.count == 0;
        _numLabel.text = [NSString stringWithFormat:@"%lu",(unsigned long)_selectAssets.count];
    }
}

- (void)resetRightButton {
    
    if (!_rightButton) {
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightButton.frame = CGRectMake(0, 0, 30, 44);
        [_rightButton addTarget:self action:@selector(rightBarButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_rightButton];
    }
    
    if (_isDeleteModel) {
        [_rightButton setImage:JFBaseBuddleImage(@"delete_normal") forState:UIControlStateNormal];
    }else {
        if ([_selectAssets containsObject:_allAssets[_currentImageIndex]]) {
            [_rightButton setImage:JFBaseBuddleImage(@"photo_select_highlight") forState:UIControlStateNormal];
        }else {
            [_rightButton setImage:JFBaseBuddleImage(@"photo_select_nomal") forState:UIControlStateNormal];
        }
    }
}

#pragma mark - Getter

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,
                                                                             0,
                                                                             CGRectGetWidth([UIScreen mainScreen].bounds),
                                                                             CGRectGetHeight([UIScreen mainScreen].bounds))
                                             collectionViewLayout:flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.pagingEnabled = YES;
        _collectionView.backgroundColor = [UIColor colorWithHexString:@"#eaebec"];
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:kCellReuseIdentifier];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenOrDisplayBarHandel)];
        tap.delegate = self;
        [_collectionView addGestureRecognizer:tap];
    }
    return _collectionView;
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight([UIScreen mainScreen].bounds) - kBottomViewHeight, CGRectGetWidth([UIScreen mainScreen].bounds), kBottomViewHeight)];
        _bottomView.backgroundColor = [UIColor colorWithHexString:@"#f4f5f6"];
        _bottomView.userInteractionEnabled = YES;
        [self.view addSubview:_bottomView];
        
        UIButton *completeButton = [[UIButton alloc]init];
        completeButton.titleLabel.font = [UIFont systemFontOfSize:15];
        completeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [completeButton setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:UIControlStateNormal];
        [completeButton setTitle:JFBaseLocalizedString(@"完成") forState:UIControlStateNormal];
        [completeButton addTarget:self action:@selector(popViewController) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:completeButton];
        [completeButton sizeToFit];
        completeButton.backgroundColor = [UIColor clearColor];
        completeButton.frame = CGRectMake(CGRectGetWidth(_bottomView.frame)-CGRectGetWidth(completeButton.frame)-10, 0, CGRectGetWidth(completeButton.frame), CGRectGetHeight(_bottomView.frame));
        
        _numLabel = [[UILabel alloc]init];
        [_bottomView insertSubview:_numLabel belowSubview:completeButton];
        _numLabel.font = [UIFont systemFontOfSize:18];
        _numLabel.textAlignment = NSTextAlignmentCenter;
        _numLabel.textColor = HexColor(@"#ffffff");
        _numLabel.backgroundColor = [UIColor colorWithHexString:@"#ff5a23"];
        _numLabel.frame = CGRectMake(CGRectGetMinX(completeButton.frame)-30, (CGRectGetHeight(_bottomView.frame) - 24) / 2.0, 24, 24);
        _numLabel.layer.cornerRadius = CGRectGetWidth(_numLabel.frame) / 2.0;
        _numLabel.layer.masksToBounds = YES;
        [self setNumLabelContent];
    
        completeButton.frame = CGRectMake(CGRectGetMinX(completeButton.frame) - CGRectGetWidth(_numLabel.frame), 0, CGRectGetWidth(completeButton.frame) + CGRectGetWidth(_numLabel.frame), CGRectGetHeight(_bottomView.frame));

        
        UILabel *topLine = [[UILabel alloc]init];
        topLine.backgroundColor = [UIColor colorWithHexString:@"#dddddd"];
        [_bottomView addSubview:topLine];
        topLine.frame = CGRectMake(0, 0, CGRectGetWidth(_bottomView.frame), 0.5);
    }
    return _bottomView;
}
@end
